package org.viva.action.cms;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.viva.core.api.Ajax;
import org.viva.service.cms.FileEditService;

import net.sf.json.JSONArray;

@Controller
public class FileEditAction {

    @Resource
    private FileEditService fileEditService;

    @RequestMapping("/cms/fileedit")
    public String index(HttpServletRequest request, ModelMap modelMap) {
        return "cms/fileedit";
    }

    @RequestMapping("/cms/fileedit/filelist")
    @ResponseBody
    public JSONArray filelist(HttpServletRequest request) {
        String root = request.getSession().getServletContext().getRealPath("/");
        String dir = request.getParameter("id");
        if (dir == null || "#".equals(dir)) {
            dir = "";
        }
        JSONArray array = fileEditService.toDir(root, dir);
        return array;
    }

    @RequestMapping("/cms/fileedit/load")
    @ResponseBody
    public Map<String, Object> load(HttpServletRequest request) throws FileNotFoundException, IOException {
        String root = request.getSession().getServletContext().getRealPath("/");
        String dir = request.getParameter("id");
        File file = new File(root + dir);
        if (file.isDirectory()) {
            Map<String, Object> m = new HashMap<>();
            m.put("type", "dir");
            m.put("content", "");
            return m;
        }
        Map<String, Object> m = new HashMap<>();
        m.put("type", getExtensionName(file.getName()));
        if (ArrayUtils.contains(imgtype, m.get("type"))) {
            m.put("content", file.getAbsolutePath().replace(root, ""));
        } else {
            m.put("content", FileCopyUtils.copyToString(new FileReader(file)));
        }
        return m;
    }

    @RequestMapping("/cms/fileedit/down")
    public ResponseEntity<byte[]> get(HttpServletRequest request) throws IOException {
        String root = request.getSession().getServletContext().getRealPath("/");
        String dir = request.getParameter("id");
        File file = new File(root + dir);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", file.getName());
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    private static String[] imgtype = new String[] { "png", "jpg", "jpeg", "bmp", "gif" };

    @RequestMapping("/cms/fileedit/save")
    @ResponseBody
    public Map<String, Object> save(HttpServletRequest request) throws IOException {
        String root = request.getSession().getServletContext().getRealPath("/");
        String dir = request.getParameter("path");
        String text = request.getParameter("content");
        File file = new File(root + dir);
        FileCopyUtils.copy(text, new FileWriter(file));
        return Ajax.exec();
    }

    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
}
